import * as ProgressPrimitive from "@radix-ui/react-progress";
import { cva, type VariantProps } from "class-variance-authority";
import type * as React from "react";

import { cn } from "@/lib/utils";

const progressVariants = cva("relative w-full overflow-hidden rounded-full", {
	variants: {
		variant: {
			default: "bg-primary/20",
			success: "bg-green-500/20",
			warning: "bg-yellow-500/20",
			destructive: "bg-destructive/20",
			secondary: "bg-secondary/40",
		},
	},
	defaultVariants: {
		variant: "default",
	},
});

const progressIndicatorVariants = cva("h-full w-full flex-1 transition-all", {
	variants: {
		variant: {
			default: "bg-primary",
			success: "bg-green-500",
			warning: "bg-yellow-500",
			destructive: "bg-destructive",
			secondary: "bg-secondary",
		},
	},
	defaultVariants: {
		variant: "default",
	},
});

interface ProgressProps
	extends React.ComponentProps<typeof ProgressPrimitive.Root>,
		VariantProps<typeof progressVariants> {
	value?: number;
	label?: string;
	showValue?: boolean;
	formatValue?: (value: number) => string;
}

function Progress({
	className,
	variant,
	value = 0,
	label,
	showValue = false,
	formatValue = (val) => `${val}%`,
	...props
}: ProgressProps) {
	const showText = label || showValue;

	return (
		<ProgressPrimitive.Root
			data-slot="progress"
			className={cn(
				progressVariants({ variant }),
				"relative w-full overflow-hidden rounded",
				showText ? "h-8" : "h-2",
				className,
			)}
			{...props}
		>
			<ProgressPrimitive.Indicator
				data-slot="progress-indicator"
				className={cn(
					progressIndicatorVariants({ variant }),
					"h-full w-full flex-1 transition-all",
				)}
				style={{ transform: `translateX(-${100 - value}%)` }}
			/>
			{showText && (
				<div className="absolute inset-0 flex items-center justify-between px-2 text-xs">
					<span className="text-primary-foreground">{label}</span>
					{showValue && (
						<span className="text-primary-foreground">
							{formatValue(value)}
						</span>
					)}
				</div>
			)}
		</ProgressPrimitive.Root>
	);
}

export { Progress, progressVariants };
